/*
 * -------------------------------------------------------------------------
 * WebSocket服务
 * -------------------------------------------------------------------------
 */

/*app对象实例*/
let app;
const { WebSocketServer } = require('ws');
const configs             = require('../package.json').configs;
const IPC_TASKLIST        = require('./ipc/dict').IPC_TASKLIST;
const utilTasklist        = require('../utils/tasklist');

/**
 * 初始化
 * @param appInstance
 */
function initialize (appInstance) {
    /*复写app实例*/
    app = appInstance;
    
    /*创建*/
    app.$ws = new WebSocketServer({ host: '127.0.0.1', port: configs.production.webSocketPort });
    
    /*已连接*/
    app.$ws.on('connection', (ws, req) => {
        /*频道*/
        let channel = req.url.split('/')[1];
        
        /*接收消息*/
        ws.on('message', msg => {
            msg = JSON.parse(msg);
            
            switch (channel) {
                /*任务管理器*/
                case IPC_TASKLIST.CHANNEL:
                    utilTasklist.entrance(ws, msg);
                    break;
            }
        });
    });
    
    /*错误*/
    app.$ws.on('error', err => console.log(err));
}

/**
 * 导出
 * @type {{initialize: initialize}}
 */
module.exports = {
    initialize
};
